const qiniuUploader = require("../utils/qiniuUploader");
const imglists = []
// 引入request请求
import { request } from '../utils/http';

const API = {
  
    //获取七牛云token
    qiniuToken(data) {
      return request('/common/qiniuToken', data); 
    },
    // 多图片上传
    uploadimgs(data,token){
      
       wx.uploadFile({
          url: 'https://up-z0.qiniup.com',
          name: 'file',
          filePath: data[i].url,
          header: {
            "Content-Type": "multipart/form-data"
          },
          formData: {
            token: token,
          },
          success: function(res) {
            wx.hideLoading();
            let data = JSON.parse(res.data)
            var imginfo = {
              file_path:"http://oss.benxinkeji.cn/"+data.key,
              file_size:data.fsize,
              file_extension_name:"png"
            }
            imglists.push(imginfo)
          },

      })
    },
   /**
  * 图片上传七牛云
  */
  uploadQiniu(tempFilePaths){

    return new Promise((presolve, preject) => {
      var t = this
      t.qiniuToken().then(res=>{
        let token = res.data.token
        let uploads = []
        wx.showLoading({
          title: '上传中...',
          mask: true,
        })
        tempFilePaths.forEach((item,i)=>{
          uploads[i] =new Promise ((resolve)=>{
            wx.uploadFile({
              url:'https://up-z0.qiniup.com',
              filePath: item.url,
              name: 'file',
              header:{
                'Content-Type':'multipart/form-data'
              },
              formData:{
                token:token,
              },
              success(res){
                var data = JSON.parse(res.data)
                var imginfo = {
                  file_path:"http://oss.benxinkeji.cn/"+data.key,
                  file_size:data.fsize,
                  file_extension_name:item.url.split(".")[item.url.split(".").length-1]
                }
                resolve(imginfo)
              },
              fail(err){
                console.log(err)
                wx.hideLoading()
              }
            })
          })
        })
        Promise.all(uploads).then(res=>{
          //图片上传完成
          console.log(res)
          presolve(res)
          wx.hideLoading()
        }).catch(err=>{
          preject(err)
          wx.hideLoading()
          wx.showToast({
            title:'上传失败请重试',
            icon:'none'
          })
        })
      })
    })
  }
}


module.exports = {
    API: API
}